<?php

namespace backend\controllers;

use Yii;
use backend\models\User;
use backend\controllers\UserSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use backend\models\PasswordResetRequestForm;
use backend\models\ResetPasswordForm;
use backend\models\SignupForm;
use backend\models\AuthAssignment;

/**
 * UserController implements the CRUD actions for User model.
 */
class UserController extends Controller
{
    public $allparentid=[];
    public $needSelected='';
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
            'access'=>[
                'class'=> \backend\components\PermissionBehavior::className(),


            ]
        ];
    }
    public function beforeAction($action)
    {
        $needSelected=0;
//        $user = new User();
        if(null !== Yii::$app->request->get('id')){
            $role = AuthAssignment::find()->where(['user_id'=>Yii::$app->request->get('id')])->one();
            $needSelected=User::findOne(Yii::$app->request->get('id'))->parentid;
            if(!empty($role)){
                if($role->item_name=='一级审批人'){
                    $allparents = User::find()->leftjoin('auth_assignment','auth_assignment.user_id=user.id')->where('auth_assignment.item_name="二级审批人" ')->select("user.id,user.realname")->all();


                }elseif($role->item_name=='二级审批人'){
                    $allparents = User::find()->leftjoin('auth_assignment','auth_assignment.user_id=user.id')->where('auth_assignment.item_name="三级审批人" ')->select("user.id,user.realname")->all();


                }else{
                    $allparents=[];
                }
            }else{
                $allparents=[];
            }

        }else{
            $allparents=[];
        }


        $allparentid  = ['0'=>'请选择'];
        foreach($allparents as $item){
            $allparentid[$item->id] = $item->realname;
        }


//        $needSelected = Yii::$app->request->get("nextid");

        $this->allparentid=$allparentid;

        $this->needSelected=$needSelected;

        return parent::beforeAction($action); // TODO: Change the autogenerated stub
    }
    /**
     * Lists all User models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new UserSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'allparentid'=>$this->allparentid,
            'needSelected'=>$this->needSelected,
        ]);
    }

    /**
     * Displays a single User model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
//    public function actionView($id)
//    {
//        return $this->render('view', [
//            'model' => $this->findModel($id),
//        ]);
//    }

    /**
     * Creates a new User model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
//    public function actionCreate()
//    {
//        $model = new User();
//
//        if ($model->load(Yii::$app->request->post()) && $model->save()) {
//            return $this->redirect(['view', 'id' => $model->id]);
//        }
//
//        return $this->render('create', [
//            'model' => $model,
//        ]);
//    }

    /**
     * Updates an existing User model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
//        Yii::$app->request->post('User')['created_at']=strtotime(Yii::$app->request->post('User')['created_at']);
//        Yii::$app->request->post('User')['updated_at']=strtotime(date('Y-m-d H:i:s'));
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['update', 'id' => $model->id]);
        }

        return $this->render('update', [
            'model' => $model,
            'allparentid'=>$this->allparentid,
            'needSelected'=>$this->needSelected,
        ]);
    }

    /**
     * Deletes an existing User model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();
        Yii::$app->session->setFlash("success",'删除成功');
        return $this->redirect(['index']);
    }

    /**
     * Finds the User model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return User the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = User::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
    /**
     * Signs user up.
     *
     * @return mixed
     */
    public function actionSignup()
    {
        $model = new SignupForm();
        if ($model->load(Yii::$app->request->post())) {
            if ($user = $model->signup()) {
                return  $this->redirect('/user/index');
                //if (Yii::$app->getUser()->login($user)) {
//                    return $this->goHome();
               // }
            }
        }

        return $this->render('signup', [
            'model' => $model,
        ]);
    }
    /**
     * Requests password reset.
     *
     * @return mixed
     */
    public function actionRequestPasswordReset()
    {
        $model = new PasswordResetRequestForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail()) {
                Yii::$app->session->setFlash('success', 'Check your email for further instructions.');

                return $this->goHome();
            } else {
                Yii::$app->session->setFlash('error', 'Sorry, we are unable to reset password for the provided email address.');
            }
        }

        return $this->render('requestPasswordResetToken', [
            'model' => $model,
        ]);
    }

    /**
     * Resets password.
     *
     * @param string $token
     * @return mixed
     * @throws BadRequestHttpException
     */
    public function actionResetPassword($token)
    {
        try {
            $model = new ResetPasswordForm($token);
        } catch (InvalidParamException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }

        if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
            Yii::$app->session->setFlash('success', 'New password saved.');

            return $this->goHome();
        }

        return $this->render('resetPassword', [
            'model' => $model,
        ]);
    }

    public function actionResetMyPassword(){
        $user = User::findOne(Yii::$app->user->id);

        if (!User::isPasswordResetTokenValid($user->password_reset_token)) {
            $user->generatePasswordResetToken();
            if (!$user->save()) {
                var_dump($user->getErrors());
                return false;
            }
        }

        $token = $user->password_reset_token;

        try {
            $model = new ResetPasswordForm($token);
        } catch (InvalidParamException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }

        if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
            Yii::$app->session->setFlash('success', 'New password saved.');

            return $this->goHome();
        }

        return $this->render('resetPassword', [
            'model' => $model,
        ]);
    }


}
